package com.meeting.manager.net;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.support.v4.app.Fragment;
import android.widget.ImageView;

import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.baidu.platform.comapi.map.A;
import com.meeting.manager.tools.L;
import com.meeting.manager.tools.P;
import com.meeting.manager.tools.T;

public class MeetingNet {

	// public static final String base_url =
	// "http://dengkun.oicp.net/MeetingManage/";
	public static String ip = "dengkun.oicp.net";
	public static String base_url = "http://" + ip + "/MeetingManage/";
	public static final int LoginSuccess = 001;
	public static final int RegistSuccess = 002;
	public static final int SUCCESS = 003;
	public static final int SUCCESS1 = 006;
	public static final int FRIENDSUCCESS = 005;
	public static final int FAILD = 004;
	public static final int MOBILENET = 0;
	public static final int WIFI = 1;
	public static final int UNKNOW = 2;
	// Intent
	public static final String INTENTLOGIN = "login"; // 退出全部Activity到Login

	public static final int post = Request.Method.POST;
	public static final int get = Request.Method.GET;

	public static void setIp(String address) {
		ip = address;
	}

	/**
	 * 以普通的post方式进行提交
	 * 
	 * @param context
	 * @param str_url
	 * @param type
	 * @param params
	 */
	public static void doPostWithHandleError(final Fragment fragment, String str_url, final int type,
			final Map<String, String> params) {
		final NetworkCallBack callBack = (NetworkCallBack) fragment;
		RequestQueue requestQueue = VolleySingleton.getInstance(fragment.getActivity()).getRequestQueue();
		StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://" + ip + "/MeetingManage/" + str_url,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						L.debug("TAG", response);
						try {
							JSONObject jsonObject = new JSONObject(response);
							String code = jsonObject.getString("code");
							// String message = jsonObject.getString("message");
							switch (code) {
							case "100":
								// String data = null;
								// data =
								// jsonObject.getJSONObject("data").toString();
								callBack.networkSuccess(type, response);
								break;

							default:
								break;
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// L.error("TAG", error.getMessage());
						// if (!MeetingNet.checkNetworkState(fragment
						// .getActivity())) {
						// T.show(fragment.getActivity(), "网络未连接，请检查您的网络");
						// } else {
						// T.show(fragment.getActivity(), "加载失败，请重新加载");
						// }
						callBack.networkFailure(type, error);
					}
				}) {
			@Override
			protected Map<String, String> getParams() {
				// 在这里设置需要post的参数
				return params;
			}
		};
		requestQueue.add(stringRequest);
	}

	/**
	 * 以普通的post方式进行提交
	 * 
	 * @param context
	 * @param str_url
	 * @param type
	 * @param params
	 */
	public static void doPostWithHandleError(final Context context, String str_url, final int type,
			final Map<String, String> params) {
		final NetworkCallBack callBack = (NetworkCallBack) context;
		RequestQueue requestQueue = VolleySingleton.getInstance(context).getRequestQueue();
		// L.debug("params", params.toString());
		StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://" + ip + "/MeetingManage/" + str_url,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						L.debug("response", response);
						try {
							JSONObject jsonObject = new JSONObject(response.toString());
							String code = jsonObject.getString("code");
							// String message = jsonObject.getString("message");
							switch (code) {
							case "100":
								// String data = null;
								// data =
								// jsonObject.getJSONObject("data").toString();
								callBack.networkSuccess(type, response);
								break;
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// L.error("Volley", error.getMessage());
						// if (!MeetingNet.checkNetworkState(context)) {
						// T.show(context, "网络未连接，请检查您的网络");
						// } else {
						// T.show(context, "加载失败，请重新加载");
						// }
						callBack.networkFailure(type, error);
					}
				}) {
			@Override
			protected Map<String, String> getParams() {
				// 在这里设置需要post的参数
				return params;
			}
		};
		L.error("error", stringRequest.toString());
		requestQueue.add(stringRequest);
	}

	public static void doPost(final Context context, final NetworkCallBack callBack, String str_url, final int type,
			final Map<String, String> params) {
		RequestQueue requestQueue = VolleySingleton.getInstance(context).getRequestQueue();
		StringRequest stringRequest = new StringRequest(Request.Method.POST, str_url, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				try {
					JSONObject jsonObject = new JSONObject(response);
					String code = jsonObject.getString("code");
					String message = jsonObject.getString("message");
					switch (code) {
					case "100":
						// String data = null;
						// data =
						// jsonObject.getJSONObject("data").toString();
						callBack.networkSuccess(type, response);
						break;
					case "200":
					case "119":
						T.show(context, message);
						break;
					default:
						// 错误处理
						T.show(context, message);
						break;
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				if (!MeetingNet.checkNetworkState(context)) {
					T.show(context, "网络未连接，请检查您的网络");
				} else {
					T.show(context, "加载失败，请重新加载");
				}
				callBack.networkFailure(type, error);
			}
		}) {
			@Override
			protected Map<String, String> getParams() {
				// 在这里设置需要post的参数
				return params;
			}
		};
		requestQueue.add(stringRequest);
	}

	/**
	 * 以json串的post请求方式进行提交
	 * 
	 * @param context
	 * @param str_url
	 * @param type
	 * @param params
	 */
	public static void doJsonPost(Context context, String str_url, final int type, final Map<String, String> params) {
		final NetworkCallBack callBack = (NetworkCallBack) context;
		RequestQueue requestQueue = VolleySingleton.getInstance(context).getRequestQueue();
		JSONObject jsonObject = new JSONObject(params);
		JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Method.POST, str_url, jsonObject,
				new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject response) {
						L.debug("TAG", response.toString());
						callBack.networkSuccess(type, response);
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						L.error("TAG", error.getMessage());
						callBack.networkFailure(type, error);
					}
				}) {
			// 注意此处override的getParams()方法,在此处设置post需要提交的参数根本不起作用
			// 必须象上面那样,构成JSONObject当做实参传入JsonObjectRequest对象里
			// 所以这个方法在此处是不需要的
			// @Override
			// protected Map<String, String> getParams() {
			// Map<String, String> map = new HashMap<String, String>();
			// map.put("name1", "value1");
			// map.put("name2", "value2");

			// return params;
			// }

			@Override
			public Map<String, String> getHeaders() {
				HashMap<String, String> headers = new HashMap<String, String>();
				headers.put("Accept", "application/json");
				headers.put("Content-Type", "application/json; charset=UTF-8");

				return headers;
			}
		};
		requestQueue.add(jsonRequest);
	}

	public static void doGet(Context context, String str_url, final int type) {
		final NetworkCallBack callBack = (NetworkCallBack) context;

		// 1 创建RequestQueue对象
		RequestQueue mRequestQueue = Volley.newRequestQueue(context);
		// 2 创建StringRequest对象
		StringRequest mStringRequest = new StringRequest(str_url, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				L.debug("TAG", response.toString());
				callBack.networkSuccess(type, response);
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				L.error("TAG", error.getMessage());
				callBack.networkFailure(type, error);
			}
		});
		// 3 将StringRequest添加到RequestQueue
		mRequestQueue.add(mStringRequest);
	}

	/**
	 * 判断连接的什么网络
	 * 
	 * @param context
	 * @return
	 */
	public static int getNetworkType(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		State gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
		State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
		if (gprs == State.CONNECTED || gprs == State.CONNECTING) {
			return MOBILENET;
		}
		// 判断为wifi状态下才加载广告，如果是GPRS手机网络则不加载！
		if (wifi == State.CONNECTED || wifi == State.CONNECTING) {
			return WIFI;
		}

		return UNKNOW;
	}

	/**
	 * 检测网络是否连接
	 * 
	 * @return
	 */
	public synchronized static boolean checkNetworkState(Context context) {
		if (context == null) {

			return false;
		}
		boolean flag = false;
		// 得到网络连接信息
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		// 去进行判断网络是否连接
		if (manager.getActiveNetworkInfo() != null) {
			flag = manager.getActiveNetworkInfo().isAvailable();
		}
		if (!flag) {
			// setNetwork();
		} else {
			// isNetworkAvailable();
		}

		return flag;
	}

	/**
	 * 取得ImageLoader
	 * 
	 * @param context
	 * @return
	 */
	public static ImageLoader getImgLoader(Context context) {
		// RequestQueue requestQueue =
		// VolleySingleton.getInstance(context).getRequestQueue();
		// ImageLoader mImageLoader = new ImageLoader(requestQueue, new
		// BitmapCache());
		return VolleySingleton.getInstance(context).getImageLoader();
	}

	/**
	 * 请求图片
	 * 
	 * @param context
	 * @param url
	 * @param imageView
	 * @param defaultImgID
	 * @param failureImgID
	 */
	public static Bitmap imageRequest(Context context, String url, ImageView imageView, int defaultImgID,
			int failureImgID) {
		// RequestQueue requestQueue =
		// VolleySingleton.getInstance(context).getRequestQueue();
		ImageContainer container = getImgLoader(context).get(url,
				ImageLoader.getImageListener(imageView, defaultImgID, failureImgID));
		return container.getBitmap();
	}

	/*
	 * public static void getBitmapFromNet(Context context, String url) { final
	 * NetworkCallBack callBack = (NetworkCallBack) context; RequestQueue
	 * mRequestQueue = Volley.newRequestQueue(context); ImageRequest request =
	 * new ImageRequest(url, new Response.Listener<Bitmap>() {
	 * 
	 * @Override public void onResponse(Bitmap response) {
	 * callBack.networkSuccess(GETBIGIMAGE, response); } }, 0, 0,
	 * Config.RGB_565, new Response.ErrorListener() {
	 * 
	 * @Override public void onErrorResponse(VolleyError error) {
	 * callBack.networkFailure(GETBIGIMAGE, null); } });
	 * mRequestQueue.add(request); }
	 */

	/*
	 * public static void showImage(String url, ImageView imageView, int
	 * defaultID){ com.nostra13.universalimageloader.core.ImageLoader
	 * imageLoader =
	 * com.nostra13.universalimageloader.core.ImageLoader.getInstance();
	 * DisplayImageOptions options = new DisplayImageOptions.Builder()
	 * .showImageOnLoading(defaultID) // 设置图片下载期间显示的图片
	 * .showImageForEmptyUri(defaultID) // 设置图片Uri为空或是错误的时候显示的图片
	 * .showImageOnFail(defaultID) // 设置图片加载或解码过程中发生错误显示的图片 .cacheInMemory(true)
	 * // 设置下载的图片是否缓存在内存中 .cacheOnDisk(true) // 设置下载的图片是否缓存在SD卡中
	 * //.displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片 .build(); // 构建完成
	 * imageLoader.displayImage(url, imageView, options); }
	 */

	/**
	 * 使用此方法能够解决图片错乱问题
	 * 
	 * @param view
	 * @param defaultImageResId
	 * @param errorImageResId
	 * @param url
	 * @return
	 */
	public static ImageListener getImageListener(final ImageView view, final int defaultImageResId,
			final int errorImageResId, final String url) {
		return new ImageListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				if (errorImageResId != 0) {
					view.setImageResource(errorImageResId);
				}
			}

			@Override
			public void onResponse(ImageContainer response, boolean isImmediate) {
				if (response.getBitmap() != null) {
					// 在这里可以设置，如果想得到圆角图片的画，可以对bitmap进行加工，可以给imageview加一个
					// 额外的参数
					String urlTag = (String) view.getTag();
					if (urlTag != null && urlTag.trim().equals(url)) {
						view.setImageBitmap(response.getBitmap());
					}
				} else if (defaultImageResId != 0) {
					view.setImageResource(defaultImageResId);
				}
			}
		};
	}
}
